import http from './request.js';

class AuthManager {
    constructor() {
        this.loginForm = document.getElementById('loginForm');
        this.registerForm = document.getElementById('registerForm');
        this.errorMessage = document.querySelectorAll('.error-message');
        this.switchLinks = document.querySelectorAll('.switch-link');
        this.redirectUrl = new URLSearchParams(window.location.search).get('redirect');
        
        this.init();
    }

    init() {
        this.bindEvents();
    }

    bindEvents() {
        // 登录表单提交
        this.loginForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            await this.handleLogin();
        });

        // 注册表单提交
        this.registerForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            await this.handleRegister();
        });

        // 表单切换
        this.switchLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const targetForm = link.dataset.target;
                this.switchForm(targetForm);
            });
        });

        // 密码确认验证
        document.getElementById('confirmPassword').addEventListener('input', () => {
            this.validatePasswords();
        });
    }

    async handleLogin() {
        const email = document.getElementById('loginEmail').value;
        const password = document.getElementById('loginPassword').value;

        try {
            const result = await http.post('/login', { email, password });
            
            // 保存token
            http.setToken(result.token);
            http.setUserInfo(result.userInfo);
            
            // 登录成功，跳转到首页
            window.location.href = '/index.html';
        } catch (error) {
            this.showError(error.message || 'Login failed, please check your email and password');
        }
    }

    async handleRegister() {
        if (!this.validatePasswords()) {
            return;
        }

        const username = document.getElementById('registerUsername').value;
        const email = document.getElementById('registerEmail').value;
        const password = document.getElementById('registerPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        if (password !== confirmPassword) {
            this.showError('Passwords do not match', 'error');
            return;
        }

        try {
            await http.post('/register', { 
                name: username,
                email, 
                password 
            });
            
            // 注册成功，切换到登录表单
            this.switchForm('loginForm');
            this.showError('Registration successful! Please login.', 'success');
        } catch (error) {
            this.showError(error.message || 'Registration failed');
        }
    }

    validatePasswords() {
        const password = document.getElementById('registerPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        const passwordError = document.querySelector('.password-error');

        if (password !== confirmPassword) {
            passwordError.style.display = 'block';
            return false;
        }
        passwordError.style.display = 'none';
        return true;
    }

    switchForm(targetId) {
        document.querySelectorAll('.auth-form').forEach(form => {
            form.classList.remove('active');
        });
        document.getElementById(targetId).classList.add('active');
        this.hideError();
    }

    showError(message, type = 'error') {
        this.errorMessage.forEach(error => {
            error.textContent = message;
            error.style.display = 'block';
            error.style.color = type === 'success' ? '#52c41a' : '#ff4d4f';
        });
    }

    hideError() {
        this.errorMessage.forEach(error => {
            error.style.display = 'none';
        });
    }
}

// 初始化认证管理器
new AuthManager(); 